package it.controllocredito.frontend.activities;

import it.controllocredito.R;
import it.controllocredito.backend.SharedPreferencesHandler;
import it.controllocredito.backend.persistence.CalllogPersistenceManager;
import it.controllocredito.backend.persistence.ConfigurationPersistenceManager;
import it.controllocredito.backend.persistence.DatabaseHandler;
import it.controllocredito.backend.persistence.SogliaPersistenceManager;
import it.controllocredito.backend.persistence.bean.Configuration;
import it.controllocredito.backend.persistence.bean.RegistroChiamate;
import it.controllocredito.backend.persistence.bean.Soglia;
import it.controllocredito.backend.persistence.bean.Soglia.FrequenzaEnum;
import it.controllocredito.backend.persistence.bean.Soglia.GiornoSettimanaEnum;
import it.controllocredito.backend.persistence.bean.Soglia.TipoEnum;
import it.controllocredito.backend.persistence.bean.Soglia.UnitaDiMisuraEnum;
import it.controllocredito.backend.persistence.tables.ConfigurationTable;
import it.controllocredito.backend.persistence.tables.RegistroChiamateTable;
import it.controllocredito.backend.persistence.tables.SogliaTable;
import it.controllocredito.frontend.fragments.CallTabFragment;
import it.controllocredito.frontend.fragments.SoglieTabFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainFragmentActivity extends FragmentActivity implements ActionBar.TabListener {
	private static final int CALLS_BLOCK_SIZE = 15;
	private static final int MN_PARAMS = Menu.FIRST;
	private static final int MN_INFO = MN_PARAMS + 1;
	private static final int DROP_TABLE = MN_INFO + 1;
	private static final int CREATE_UPDATE_TABLE = DROP_TABLE + 1;
	private static final int INIZIALIZZA_TABLE_FROM_REGISTRO = CREATE_UPDATE_TABLE + 1;
	private static final int SETTINGS_RESULT = 1;

	private ProgressDialog progressDialog;
	private Context mContext;
	ArrayList<RegistroChiamate> regChiamateList;

	CallTabFragment ctf;

	SectionsPagerAdapter mSectionsPagerAdapter;
	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));

		SharedPreferencesHandler sharedPreferencesHandler = new SharedPreferencesHandler(getApplicationContext());

		if (sharedPreferencesHandler.isFirstBoot()) {
			progressDialog = ProgressDialog.show(MainFragmentActivity.this, "", "", true, false);
			Configuration configurationBean = new Configuration();
			String configurationName = "Conf_1";
			configurationBean.setNome(configurationName);

			// creo soglia associata a questa configurazione
			Soglia sogliaBean = new Soglia();
			sogliaBean.setFrequenza(FrequenzaEnum.MESE);
			sogliaBean.setGiornoMeseInizio(1);
			sogliaBean.setGiornoSettimanaInizio(GiornoSettimanaEnum.LUNEDI);
			sogliaBean.setTipo(TipoEnum.TEL);
			sogliaBean.setUnitaDiMisura(UnitaDiMisuraEnum.MINUTI);
			sogliaBean.setValore(50);

			SogliaPersistenceManager spm = new SogliaPersistenceManager(this.getApplicationContext());

			ConfigurationPersistenceManager cpm = new ConfigurationPersistenceManager(this.getApplicationContext());

			DatabaseHandler dbhandler = new DatabaseHandler(this);
			dbhandler.dropOnlyTable(ConfigurationTable.getName());
			dbhandler.dropOnlyTable(SogliaTable.getName());
			dbhandler.initDB();
			long configurationId = cpm.addConfigurazione(configurationBean);
			// aggiorno il bean con quello completo preso dal db
			spm.addSogliaToConfiguration(configurationId, sogliaBean);

			// da cancellare
			Configuration newconfiguration = dbhandler.getConfiguration(configurationId);

			Toast.makeText(this, "Distruggo tutte le tabelle", Toast.LENGTH_LONG).show();

			DatabaseHandler databaseHandler = new DatabaseHandler(this);

			databaseHandler.dropTable(RegistroChiamateTable.getName());
			// databaseHandler.dropTable(MonitorTable.getName());

			CalllogPersistenceManager calllogPersistenceManager;
			calllogPersistenceManager = new CalllogPersistenceManager(this.getApplicationContext());

			calllogPersistenceManager.cleanRegistro();

			calllogPersistenceManager.aggiornamentoRegistro();

			sharedPreferencesHandler.setNoMoreFirstBoot();

			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
		}
		// Salvo il context per poterlo usare nel task asincrono
		this.mContext = this;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// menu.add(0, MN_PARAMS, 0, "Modifica parametri");
		// menu.add(0, MN_INFO, 0, "Report");
		// menu.add(0, DROP_TABLE, 0, "Drop Table");
		// menu.add(0, CREATE_UPDATE_TABLE, 0, "Create Table");
		// menu.add(0, INIZIALIZZA_TABLE_FROM_REGISTRO, 0, "Aggiorna Chiamate");
		// Inflate the menu items for use in the action bar
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// case MN_PARAMS:
		// Intent openParamsActivity = new
		// Intent("it.controllocredito.frontend.activities.PARAMSACTIVITY");
		// openParamsActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// startActivity(openParamsActivity);
		// break;
		// case MN_INFO:
		// Intent reportIntent = new Intent(MainFragmentActivity.this,
		// ReportActivity.class);
		// startActivity(reportIntent);
		//
		// break;
		// case DROP_TABLE:
		// Toast.makeText(this, "Distruggo tutte le tabelle",
		// Toast.LENGTH_LONG).show();
		//
		// DatabaseHandler databaseHandler = new DatabaseHandler(this);
		//
		// databaseHandler.dropTable(RegistroChiamateTable.getName());
		// // databaseHandler.dropTable(MonitorTable.getName());
		// break;
		// case CREATE_UPDATE_TABLE:
		// Toast.makeText(this, "Creo e aggiorno tutte le tabelle",
		// Toast.LENGTH_LONG).show();
		// // Visualizzo il progress dialog per fare attendere l'utente
		// progressDialog = ProgressDialog.show(MainFragmentActivity.this, "",
		// "", true, false);
		// // avvio il task asincrono per aggiornare il registro chiamate
		// new TablesUpdateAsyncTask().execute();
		// /*
		// * databaseHandler.addRecord(RegistroChiamateTable.getName(),
		// * RegistroChiamateTable.createRecord( CallLog.Calls.INCOMING_TYPE,
		// * 6000, "+39", "3477229171"));
		// */
		//
		// // databaseHandler.getRecordsRegistroChiamate();
		// break;
		// case INIZIALIZZA_TABLE_FROM_REGISTRO:
		// // Visualizzo il progress dialog per fare attendere l'utente
		// progressDialog = ProgressDialog.show(MainFragmentActivity.this, "",
		// "", true, false);
		// // avvio il task asincrono per aggiornare il registro chiamate
		// new CallsUpdateAsyncTask().execute();
		// break;
		case R.id.action_edit:
			Toast.makeText(this, "Edit selected", Toast.LENGTH_SHORT).show();
			Intent reportIntent = new Intent(MainFragmentActivity.this, ReportActivity.class);
			startActivity(reportIntent);
			break;
		default:
			Intent i = new Intent(getApplicationContext(), SettingsActivity.class);
			startActivityForResult(i, SETTINGS_RESULT);
			break;
		}

		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == SETTINGS_RESULT) {
			displayUserSettings();
		}

	}

	private void displayUserSettings() {
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

		String settings = "";
		settings = settings + "\nNotify:" + sharedPrefs.getBoolean("setting_notify", false);
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			Fragment fragment = getFragment(position);
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			}
			return null;
		}
	}

	public Fragment getFragment(int position) {
		Fragment fragment = new DummySectionFragment();

		switch (position) {
		case 0:

			SharedPreferencesHandler sharedPreferencesHandler = new SharedPreferencesHandler(getApplicationContext());

			if (sharedPreferencesHandler.isFirstBoot()) {
				progressDialog = ProgressDialog.show(MainFragmentActivity.this, "", "", true, false);

				Toast.makeText(this, "Distruggo tutte le tabelle", Toast.LENGTH_LONG).show();

				DatabaseHandler databaseHandler = new DatabaseHandler(this);

				databaseHandler.dropTable(RegistroChiamateTable.getName());
				// databaseHandler.dropTable(MonitorTable.getName());

				CalllogPersistenceManager calllogPersistenceManager;
				calllogPersistenceManager = new CalllogPersistenceManager(this.getApplicationContext());

				calllogPersistenceManager.cleanRegistro();

				calllogPersistenceManager.aggiornamentoRegistro();

				sharedPreferencesHandler.setNoMoreFirstBoot();

				if (progressDialog != null) {
					progressDialog.dismiss();
				}
			}

			ctf = new CallTabFragment();
			fragment = ctf;
			break;
		case 1:
			// fragment = new SmsTabFragment();
			// break;
			// case 2:
			// fragment = new InternetTabFragment();
			// break;
			// case 3:
			fragment = new SoglieTabFragment();
			break;
		default:
			fragment = new DummySectionFragment();
			break;
		}

		return fragment;

	}

	public static class DummySectionFragment extends Fragment {
		public static final String ARG_SECTION_NUMBER = "section_number";

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_controllo_credito_main_dummy, container, false);
			TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
			dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
			return rootView;
		}
	}

	// Classe di gestione aggiornamento registro chiamate asincrono
	private class CallsUpdateAsyncTask extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... arg0) {
			callsUpdate();
			return null;
		}

		protected void onPostExecute(Object result) {
			ctf.updateFragment(MainFragmentActivity.this);
			/*
			 * // Aggiorno la listView delle chiamate
			 * RegistroChiamateArrayAdapter registroChiamateArrayAdapter = new
			 * RegistroChiamateArrayAdapter(mContext, regChiamateList); final
			 * ListView listView = (ListView) findViewById(R.id.mylist); //
			 * Assign adapter to ListView
			 * listView.setAdapter(registroChiamateArrayAdapter); //
			 * calllogPersistenceManager.aggiornamentoRegistro();
			 */
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		private void callsUpdate() {
			CalllogPersistenceManager calllogPersistenceManager;
			calllogPersistenceManager = new CalllogPersistenceManager(mContext);
			List<RegistroChiamate> listaRegistroChiamate = calllogPersistenceManager.getRecordsRegistroChiamate(1,
					CALLS_BLOCK_SIZE);

			regChiamateList = new ArrayList<RegistroChiamate>();

			int i = 0;

			for (RegistroChiamate registroChiamata : listaRegistroChiamate) {
				regChiamateList.add(registroChiamata);
				i++;
			}

		}

	}

	// Classe di gestione aggiornamento tabelle asincrono
	private class TablesUpdateAsyncTask extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... arg0) {
			tablesUpdate();
			return null;
		}

		protected void onPostExecute(Object result) {

			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}

		private void tablesUpdate() {
			CalllogPersistenceManager calllogPersistenceManager;
			calllogPersistenceManager = new CalllogPersistenceManager(mContext);
			calllogPersistenceManager.cleanRegistro();
			calllogPersistenceManager.aggiornamentoRegistro();
		}

	}

}
